package com.system.core.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;

public class ControllerBase {
	private static final ThreadLocal<HttpServletRequest> requestContainer = new ThreadLocal<HttpServletRequest>();
	private static final ThreadLocal<HttpServletResponse> responseContainer = new ThreadLocal<HttpServletResponse>();
	private static final ThreadLocal<ModelMap> modelContainer = new ThreadLocal<ModelMap>();

	@ModelAttribute
	private final void init(HttpServletResponse response, HttpServletRequest request, ModelMap model) {
		responseContainer.set(response);
		requestContainer.set(request);
		modelContainer.set(model);
	}
	
	public String getErrorLastMsg(BindingResult bindingResult) {
		return bindingResult.getAllErrors().get(0).getDefaultMessage();
	}

	protected final HttpServletResponse getResponse() {
		return responseContainer.get();
	}

	protected final HttpServletRequest getRequest() {
		return requestContainer.get();
	}

	protected final ModelMap getModelMap() {
		return modelContainer.get();
	}
	
	public void setPageResult(Object result) {
		getModelMap().put("pageResult", result);
	}
}
